/* Copyright 2024 Coremail
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const FILE_SCHEME = "file://"
const INLINE_IMG_WIDTH = 200
const INLINE_IMG_HEIGHT = 200

import { RandomUtil } from '@ohos/base/src/main/ets/utils/RandomUtil'
import type { InlineAttachment } from '@ohos/mail-app/src/main/ets/app'

export class RichEditorUtil {
  static replaceContent(content: string): string {
    content = content.substring(1, content.length - 1); // 去掉前后引号
    content = content.replace(/\\u003C/g, "<");
    content = content.replace(/\\\"/g, '"');
    content = content.replace(/\\n/g, '\n');
    return content;
  }

  static replaceImg(content: string, inlineAttachments: Array<InlineAttachment>): string {
    content = content.replace(/<img.*?src=\"(.*?)\"[^>]*>/g, (s, filename: string) => {
      // content = content.replace(/<img.*?src=\"(.*?)\">/g, function(s, filename: string) {
      let cid: string = RandomUtil.generateRandomNumberStr(13)
      let imgInsert: string = "img_insert_" + cid;
      let inlineImage: InlineAttachment = { contentId: cid,
        file: filename.substring(FILE_SCHEME.length, filename.length) };

      inlineAttachments.push(inlineImage);
      return `<img src="cid:${cid}"  id="${imgInsert}" width=${INLINE_IMG_WIDTH}  height=${INLINE_IMG_HEIGHT} /> `
    })
    return content;
  }
}